package cn.edu.imust.loginregisterdemo.home.view;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.github.chrisbanes.photoview.PhotoView;
import com.uuzuche.lib_zxing.BuildConfig;

import java.net.HttpURLConnection;
import java.util.List;
import java.util.Objects;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.edu.imust.loginregisterdemo.R;
import cn.edu.imust.loginregisterdemo.base.BaseFragment;
import cn.edu.imust.loginregisterdemo.home.ListViewAdapter;
import cn.edu.imust.loginregisterdemo.home.RecyclerViewBaseAdapter;
import cn.edu.imust.loginregisterdemo.home.model.domain.Api;
import cn.edu.imust.loginregisterdemo.home.model.domain.DownDataResult;
import cn.edu.imust.loginregisterdemo.login.model.User;
import cn.edu.imust.loginregisterdemo.utils.RetrofitManager;
import cn.edu.imust.loginregisterdemo.utils.ToBase64Util;
import cn.edu.imust.loginregisterdemo.utils.Utils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends BaseFragment {

    private RecyclerView            mList;
    private RecyclerViewBaseAdapter mAdapter;
    private SwipeRefreshLayout      mRefreshLayout;
    private Api api;
    private List<DownDataResult.DataBean> data;
    private String time;
//    private String username = BmobUser.getCurrentUser(User .class).getUsername();
    private String username = "hzy630";;
    private Dialog    dialog;
    private PhotoView mPvScale;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        Bmob.initialize(getContext(), "33452dfaa0b4f1b9b1a5ea2c1818d5f4");
        //找到控件
        mList = (RecyclerView) view.findViewById(R.id.recycler_view);
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_layout);
        api = RetrofitManager.getInstance().getRetrofit().create(Api.class);
        //准备数据
        initData();
        initDialog();

        //处理下啦刷新
        handlerDownPullUpdate();
        return view;
    }


    private void initDialog() {
        dialog = new Dialog(Objects.requireNonNull(getContext()), R.style.edit_AlertDialog_style);
        dialog.setContentView(R.layout.dialog_layout);
        mPvScale = dialog.findViewById(R.id.pv_scale);
        //选择true的话点击其他地方可以使dialog消失，为false的话不会消失
        dialog.setCanceledOnTouchOutside(true); // Sets whether this dialog is
        Window window = dialog.getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        mPvScale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 执行刷新数据的操作
     */
    private void handlerDownPullUpdate() {

        mRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorViolet, R.color.colorTurquoise, R.color.colorYellow);
        mRefreshLayout.setEnabled(true);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //在这里面去执行刷新数据的操作
                /**
                 * 当我们在顶部,下拉的时候 ,这个方法就会被触发
                 * 但是,这个方法是在主线程,不可以执行耗时操作。
                 * 一般来说,我们去请求数据要开一个子线程去获取
                 * 这里面演示的话,我直接添加一条数据
                 */
                Call<DownDataResult> call = api.requestDataFirst(username);
                call.enqueue(new Callback<DownDataResult>() {
                    @Override
                    public void onResponse(Call<DownDataResult> call, Response<DownDataResult> response) {
                        int code = response.code();
                        if (BuildConfig.DEBUG) Log.d("Refresh", "code:" + code);
                        if (code == HttpURLConnection.HTTP_OK) {
                            DownDataResult body = response.body();
                            if (body != null) {
                                List<DownDataResult.DataBean> data1 = body.getData();
                                if (BuildConfig.DEBUG) Log.d("Refresh", "data size -->:" + HomeFragment.this.data.size());
                                time = HomeFragment.this.data.get(data1.size() - 1).getTime();

                                for (int i = 0; i < data1.size(); i++) {
                                    data.add(i, data1.get(i));
                                }
                                //这里要做两件事,一件是让刷新停止,另外一件则是要更新列表
                                mAdapter.notifyDataSetChanged();
                                mRefreshLayout.setRefreshing(false);
                            }

                        }
                    }

                    @Override
                    public void onFailure(Call<DownDataResult> call, Throwable t) {
                        if (BuildConfig.DEBUG)
                            Log.d("HomeFragment", "failed, " + t.toString());
                    }
                });
            }
        });

    }

    /**
     * 上拉加载更多
     */
    private void initListener() {

        mAdapter.setOnItemClickListener(new RecyclerViewBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //这里处理条目的点击事件,该干嘛就干嘛,跳转的就跳转...
                //Toast.makeText(getActivity(), "您点击的是第" + position + "个条目", Toast.LENGTH_SHORT).show();
            }

            //点击图片, 放大
            @Override
            public boolean onItemPictureClick(ImageView imageView, int position, DownDataResult.DataBean dataBean) {
                //Toast.makeText(getActivity(), "第" + position + "个条目的图片", Toast.LENGTH_SHORT).show();
                String picBase64 = dataBean.getPic();
                if (cn.edu.imust.loginregisterdemo.BuildConfig.DEBUG) Log.d("HomeFragment", picBase64);
                if (picBase64 != null) {
                    Bitmap bitmap = ToBase64Util.Base64ToBitMap(picBase64);
                    mPvScale.setImageBitmap(bitmap);
                    dialog.show();
                }

                return false;
            }

            //点击详情----->跳转至DetailActivity
            @Override
            public boolean onItemDetailClick(TextView textView, int position, DownDataResult.DataBean dataBean) {
                //Toast.makeText(getContext(), "第" + position + "个条目的详情, " + dataBean.getTime(), Toast.LENGTH_SHORT).show();
                Bundle bundle = new Bundle();
                bundle.putSerializable("dataBean", dataBean);
                if (cn.edu.imust.loginregisterdemo.BuildConfig.DEBUG) Log.d("HomeFragment", dataBean.toString());
                Intent intent = new Intent(getContext(), DetailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                return false;
            }
        });

        //这里面去处理上拉加载更多
        if (mAdapter instanceof ListViewAdapter) {
            ((ListViewAdapter) mAdapter).setOnRefreshListener(new ListViewAdapter.OnRefreshListener() {
                @Override
                public void onUpPullRefresh(final ListViewAdapter.LoaderMoreHolder loaderMoreHolder) {
                    //这里面去加载更多的数据,同样,需要在子线程中完成,这里仅作演示

                    Call<DownDataResult> call = api.requestData(username, time);
                    call.enqueue(new Callback<DownDataResult>() {
                        @Override
                        public void onResponse(Call<DownDataResult> call, Response<DownDataResult> response) {
                            int code = response.code();
                            if (BuildConfig.DEBUG) Log.d("HomeFragment", "code:" + code);
                            if (code == HttpURLConnection.HTTP_OK) {
                                DownDataResult body = response.body();
                                if (body != null) {
                                    List<DownDataResult.DataBean> data1 = body.getData();
                                    if (BuildConfig.DEBUG) Log.d("HomeFragment", "data size -->:" + HomeFragment.this.data.size());
                                    time = data1.get(data1.size() - 1).getTime();
                                    data.addAll(data1);
                                    //这里要做两件事,一件是让刷新停止,另外一件则是要更新列表
                                    mAdapter.notifyDataSetChanged();
                                    loaderMoreHolder.update(ListViewAdapter.LoaderMoreHolder.LOADER_STATE_NORMAL);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<DownDataResult> call, Throwable t) {
                            if (BuildConfig.DEBUG)
                                Log.d("HomeFragment", "failed, " + t.toString());
                            loaderMoreHolder.update(ListViewAdapter.LoaderMoreHolder.LOADER_STATE_RELOAD);
                        }
                    });

                }
            });
        }
    }


    private void initData() {
        //List<DataBea>---->Adapter------>setAdapter------>显示数据。
        Call<DownDataResult> call = api.requestDataFirst(username);
        ProgressDialog dialog = new ProgressDialog(getContext());
        dialog.setMessage("加载中.....");
        dialog.show();
        call.enqueue(new Callback<DownDataResult>() {
            @Override
            public void onResponse(Call<DownDataResult> call, Response<DownDataResult> response) {
                if (BuildConfig.DEBUG) Log.d("HomeFragment", "username-->" + username);
                int code = response.code();
                if (BuildConfig.DEBUG) Log.d("HomeFragment", "code:" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    DownDataResult body = response.body();

                    if (body != null) {
                        data = body.getData();
                        time = data.get(data.size() - 1).getTime();
                        if (BuildConfig.DEBUG) Log.d("HomeFragment", "data size -->:" + data.size());
                        //设置默认的显示样式为ListView的效果
                        showList(true, false, data);
                        dialog.dismiss();
                    }

                }

            }

            @Override
            public void onFailure(Call<DownDataResult> call, Throwable t) {
                dialog.dismiss();
                Toast.makeText(getContext(), "服务器忙, 请稍后。", Toast.LENGTH_SHORT).show();
                if (BuildConfig.DEBUG) Log.d("HomeFragment", "failed," + t.toString());
            }
        });
    }

    /**
     * 这个方法用于现实ListView一样的效果
     */
    private void showList(boolean isVertical, boolean isReverse, List<DownDataResult.DataBean> data) {
        //RecyclerView需要设置样式,其实就是设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器来控制
        //设置水平还是垂直
        layoutManager.setOrientation(isVertical ? LinearLayoutManager.VERTICAL : LinearLayoutManager.HORIZONTAL);
        //设置标准(正向)还是反向的
        layoutManager.setReverseLayout(isReverse);

        mList.setLayoutManager(layoutManager);
        //创建适配器
        if (BuildConfig.DEBUG) Log.d("HomeFragment", "data.size():" + data.size());
        mAdapter = new ListViewAdapter(data);
        //设置到RecyclerView里头
        mList.setAdapter(mAdapter);

        //初始化事件
        initListener();
    }
}
